package com.sgb.kjwl.view.ui.activity.manage

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityVrListBinding
import com.sgb.kjwl.databinding.ItemVrBinding
import com.sgb.kjwl.di.self.DaggerSelfComponent
import com.sgb.kjwl.di.self.SelfModule
import com.sgb.kjwl.model.entity.manage.PromotionalAlbumEntity
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity
import com.sgb.kjwl.viewmodel.manage.UpLoadViewModel
import com.swgk.core.base.di.AppComponent
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration
import com.swgk.core.util.ClickUtils
import com.swgk.core.util.DateUtils
import com.swgk.core.util.MToast
import com.swgk.core.util.SharedPreferenceUtil
import javax.inject.Inject
class VrListActivity : AppActivity() {

    private lateinit var mBinding : ActivityVrListBinding

    private var isLoadMore = false //是否加载更多
    private var isEnableLoadMore = false//是否能加载更多

    private var siteNo = ""
    private var siteType = 1

    @Inject
    lateinit var mViewModel : UpLoadViewModel

    lateinit var mAdapter : VrAdapter

    companion object{
        const val REQUEST_CODE = 11324;
        fun launch(context: Context){
            val intent = Intent(context, VrListActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun setupActivityComponent(appComponent: AppComponent?) {
        super.setupActivityComponent(appComponent)
        DaggerSelfComponent.builder().appComponent(appComponent)
            .selfModule(SelfModule()).build().inject(this)
    }

    override fun initView() {
        super.initView()
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_vr_list)
        mBinding.include.titleView.text = "VR全景"
        mBinding.include.ivBack.setOnClickListener { finish() }
        mBinding.include.rightView.text = "新增"
        mBinding.include.rightView.setOnClickListener {
            UploadPicAndVideoActivity.start(this, siteType, "3", REQUEST_CODE)
        }
        initRecyclerView()
        mViewModel.mVrList.observe(this, {
             isEnableLoadMore = it != null && it.size >= 20
             if (isLoadMore){
                 mAdapter.addData(it)
             } else {
                 mAdapter.setNewData(it)
             }
        })
        mViewModel.mDeletePosition.observe(this, {
            if (it != null){
                MToast.showToast(this,"删除成功")
                mAdapter.remove(it)
            }
        })
        siteType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1)
        if (siteType == 0){
            siteNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "")
        } else {
            siteNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "")
        }
    }

    @SuppressLint("UseRequireInsteadOfGet")
    private fun initRecyclerView() {
        // SwipeRefreshLayout 刷新
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                getData()
                mBinding.refreshLayout.finishLoadMore(500)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                getData()
                mBinding.refreshLayout.finishRefresh(500)
            }
        })
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinding.refreshLayout.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                return mBinding.recycleView.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                //整个View控件的高度
                val scrollRange: Int = mBinding.recycleView.computeVerticalScrollRange()
                //当前屏幕之前滑过的距离
                val scrollOffset: Int = mBinding.recycleView.computeVerticalScrollOffset()
                //当前屏幕显示的区域高度
                val scrollExtent: Int = mBinding.recycleView.computeVerticalScrollExtent()
                //获取recyclerView的高度
                val height: Int = mBinding.recycleView.height
                if (height > scrollRange) {
                    return false
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
        mBinding.recycleView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        mBinding.recycleView.setItemViewCacheSize(100)
        mBinding.recycleView.setHasFixedSize(true)
        mAdapter = VrAdapter(this, R.layout.item_vr)
        mAdapter.bindToRecyclerView(mBinding.recycleView)
        val empty = LayoutInflater.from(this).inflate(R.layout.layout_empty_view, mBinding.recycleView, false)
        mAdapter.emptyView = empty
        mBinding.recycleView.addItemDecoration(
            RecyclerCustomDecoration(
                0f,
                0f,
                0f,
                resources.getDimension(R.dimen.dp1), resources.getColor(R.color.color_main_bg)
            )
        )
        mAdapter.setCallBack(object : ClickCallback{
            override fun deleteItem(item: PromotionalAlbumEntity?, position: Int) {
                 if (item != null){
                     mViewModel.deleteVr("" + item.id, position)
                 }
            }

            override fun editItem(item: PromotionalAlbumEntity?, position: Int) {
                if (item != null){
                    UploadPicAndVideoActivity.start(this@VrListActivity, siteType, "3", item, REQUEST_CODE)
                }
            }

            override fun clickItem(item: PromotionalAlbumEntity?, position: Int) {
                if (!ClickUtils.isDoubleClick()) {
                    if (item != null && !TextUtils.isEmpty(item.vrUrl)) {
                        WebViewX5HostActivity.start(this@VrListActivity, item.vrUrl)
                    }
                }
            }
        })
    }

    fun getData(){
        mViewModel.getVrList(siteNo, siteType, isLoadMore, 3)
    }

    override fun init() {
        super.init()
        isLoadMore = false
        getData()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK){
            isLoadMore = false
            getData()
        }
    }


    class VrAdapter(context : Activity, layoutResId : Int) : BaseQuickAdapter<PromotionalAlbumEntity, BaseViewHolder>(layoutResId){
        private var context : Activity ?= null
        init {
           this.context = context
        }
        private var mItemBinding : ItemVrBinding ?= null
        private var mColorSpan : ForegroundColorSpan = ForegroundColorSpan(context.resources.getColor(R.color.color_title_medium))
        private var ssb : SpannableStringBuilder ?= null
        private var mCallback : ClickCallback ?= null
        fun setCallBack(callback : ClickCallback){
            this.mCallback = callback
        }

        override fun convert(helper: BaseViewHolder?, item: PromotionalAlbumEntity?) {
            mItemBinding = DataBindingUtil.bind(helper!!.itemView)
            if (mItemBinding != null){
                mItemBinding!!.entity = item
                setColorSpan(mContext.resources.getString(R.string.vr_upload_user, if(TextUtils.isEmpty(item!!.uploaderName)) "" else item.uploaderName), mItemBinding!!.tvUser)
                setColorSpan(mContext.resources.getString(R.string.vr_upload_user, if (item.createTime == 0L) "" else DateUtils.timestampToDate(item.createTime)), mItemBinding!!.tvTime)
                mItemBinding!!.tvEdit.setOnClickListener {
                    if (mCallback != null){
                        mCallback!!.editItem(item, helper.layoutPosition)
                    }
                }
                mItemBinding!!.tvDelete.setOnClickListener {
                    if (mCallback != null){
                        mCallback!!.deleteItem(item, helper.layoutPosition)
                    }
                }
                mItemBinding!!.root.setOnClickListener {
                    if (mCallback != null){
                        mCallback!!.clickItem(item, helper.layoutPosition)
                    }
                }
                Glide.with(mContext).load(item.url).error(R.mipmap.bg_jyb_error_iamge).placeholder(R.mipmap.bg_jyb_error_iamge).into(mItemBinding!!.ivPic)
            }
        }

        private fun setColorSpan(content: String, tv: TextView) {
            ssb = SpannableStringBuilder(content)
            ssb!!.setSpan(mColorSpan, content.indexOf("："), content.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
            tv.text = ssb
        }

    }

    interface ClickCallback{
        fun deleteItem(item: PromotionalAlbumEntity?, position : Int)
        fun editItem(item: PromotionalAlbumEntity?, position : Int)
        fun clickItem(item: PromotionalAlbumEntity?, position : Int)
    }


}